package net.hserver.file.controller;

import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.plugin.web.annotation.WebSocket;
import cn.hserver.plugin.web.handlers.Ws;
import cn.hserver.plugin.web.interfaces.WebSocketHandler;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import net.hserver.file.bean.Msg;
import net.hserver.file.bean.PeerJsData;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static net.hserver.file.bean.Msg.Type.OPEN;

@WebSocket("/peerjs")
@Slf4j
public class WebSocketController implements WebSocketHandler {
    public static final Map<String, PeerJsData> ONLINE_USER = new ConcurrentHashMap<>();

    @Override
    public void onConnect(Ws ws) {
        String id = ws.query("id");
        String key = ws.query("key");
        String token = ws.query("token");
        String version = ws.query("version");
        PeerJsData peerJsData = new PeerJsData(id, key, token, version, ws);
        ONLINE_USER.put(id, peerJsData);
        ws.send(new Msg(OPEN).getJson());
    }

    @Override
    public void onMessage(Ws ws) {
        JSONObject entries = JSONUtil.parseObj(ws.getMessage());
        switch (Msg.Type.valueOf(entries.getStr("type"))) {
            case HEARTBEAT:
                log.info("收到心跳包：{}", ws.query("id"));
                break;
            default:
                log.info(ws.getMessage());
                String dst = entries.getStr("dst");
                entries.set("src", ws.query("id"));
                ONLINE_USER.get(dst).getWs().send(entries.toString());
                break;
        }

    }

    @Override
    public void disConnect(Ws ws) {
        ws.getCtx().close();
        String id = ws.query("id");
        ONLINE_USER.remove(id);
    }
}
